import { Request, Response } from 'express';
import cacheService from '@/services/monitor/cache.service';
import ApiResponse from '@/utils/api/api-response.util';
import { getLogger } from '@/utils/logger';
import { AuthRequest } from '@/types';

// 创建模块专用的日志记录器
const consoleLogger = getLogger("cache-controller");
const logger = getLogger("cache-controller", {
	console: false,
});

class CacheController {
  /**
   * 获取Redis基本信息、dbSize、命令统计
   * @param req 请求对象
   * @param res 响应对象
   */
  public async getInfo(req: Request, res: Response){
    try {
      // 请求日志
      consoleLogger.info("获取缓存基本信息请求", {
        operator: req.user?.userName || 'unknown',
      });
      
      const data = await cacheService.getInfo();
      
      // 结果日志
      logger.info("获取缓存基本信息成功", {
        response: {
          info: data?.info ? true : false,
          dbSize: data?.dbSize,
          commandStats: data?.commandStats?.length || 0,
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, data);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`获取缓存信息失败: ${error instanceof Error ? error.message : String(error)}`, {
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, error instanceof Error ? error.message : '获取缓存信息失败');
      }
    }
  }

  /**
   * 获取常用缓存名称列表
   * @param req 请求对象
   * @param res 响应对象
   */
  public async getNames(req: Request, res: Response) {
    try {
      // 请求日志
      consoleLogger.info("获取缓存名称列表请求", {
        operator: req.user?.userName || 'unknown',
      });
      
      const data = await cacheService.getNames();
      
      // 结果日志
      logger.info("获取缓存名称列表成功", {
        response: {
          count: data?.length || 0,
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, data);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`获取缓存名称失败: ${error instanceof Error ? error.message : String(error)}`, {
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, error instanceof Error ? error.message : '获取缓存名称失败');
      }
    }
  }

  /**
   * 获取指定缓存名下所有key
   * @param req 请求对象
   * @param res 响应对象
   */
  public async getKeys(req: Request, res: Response) {
    try {
      const { cacheName } = req.params;
      
      // 请求日志
      consoleLogger.info("获取缓存键列表请求", {
        params: req.params,
        cacheName,
        operator: req.user?.userName || 'unknown',
      });
      
      const data = await cacheService.getKeys(cacheName);
      
      // 结果日志
      logger.info("获取缓存键列表成功", {
        response: {
          cacheName,
          count: data?.length || 0,
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, data);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`获取缓存key失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          params: req.params,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, error instanceof Error ? error.message : '获取缓存key失败');
      }
    }
  }

  /**
   * 获取指定key的值
   * @param req 请求对象
   * @param res 响应对象
   */
  public async getValue(req: Request, res: Response) {
    try {
      const { cacheName, cacheKey } = req.params;
      
      // 请求日志
      consoleLogger.info("获取缓存值请求", {
        params: req.params,
        cacheName,
        cacheKey,
        operator: req.user?.userName || 'unknown',
      });
      
      const data = await cacheService.getValue(cacheName, cacheKey);
      
      // 结果日志
      logger.info("获取缓存值成功", {
        response: {
          cacheName,
          cacheKey,
          hasValue: data !== null && data !== undefined,
        },
        operator: req.user?.userName || 'unknown',
      });
      
      ApiResponse.success(res, data);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`获取缓存值失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          params: req.params,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, error instanceof Error ? error.message : '获取缓存值失败');
      }
    }
  }

  /**
   * 清理指定缓存名下所有key
   * @param req 请求对象
   * @param res 响应对象
   */
  public async clearCacheName(req: AuthRequest, res: Response) {
    try {
      const { cacheName } = req.params;
      const operator = req.user?.userName || 'admin';
      
      // 请求日志
      consoleLogger.info("清理缓存名下所有键请求", {
        params: req.params,
        cacheName,
        operator,
      });
      
      await cacheService.clearCacheName(cacheName);
      
      // 结果日志
      logger.info("清理缓存名下所有键成功", {
        response: {
          cacheName,
        },
        operator,
      });
      
      ApiResponse.success(res);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`清理缓存失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          params: req.params,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, error instanceof Error ? error.message : '清理缓存失败');
      }
    }
  }

  /**
   * 清理指定key
   * @param req 请求对象
   * @param res 响应对象
   */
  public async clearCacheKey(req: AuthRequest, res: Response) {
    try {
      const { cacheKey } = req.params;
      const operator = req.user?.userName || 'admin';
      
      // 请求日志
      consoleLogger.info("清理缓存键请求", {
        params: req.params,
        cacheKey,
        operator,
      });
      
      await cacheService.clearCacheKey(cacheKey);
      
      // 结果日志
      logger.info("清理缓存键成功", {
        response: {
          cacheKey,
        },
        operator,
      });
      
      ApiResponse.success(res, null, '清理成功');
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`清理缓存键失败: ${error instanceof Error ? error.message : String(error)}`, {
        requestData: {
          params: req.params,
        },
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, error instanceof Error ? error.message : '清理缓存键失败');
      }
    }
  }

  /**
   * 清理所有缓存
   * @param req 请求对象
   * @param res 响应对象
   */
  public async clearCacheAll(req: AuthRequest, res: Response) {
    try {
      const operator = req.user?.userName || 'admin';
      
      // 请求日志
      consoleLogger.info("清理所有缓存请求", {
        operator,
      });
      
      await cacheService.clearCacheAll();
      
      // 结果日志
      logger.info("清理所有缓存成功", {
        operator,
      });
      
      ApiResponse.success(res);
    } catch (error) {
      // 详细的错误日志
      consoleLogger.error(`清理缓存失败: ${error instanceof Error ? error.message : String(error)}`, {
        operator: req.user?.userName || 'unknown',
        stack: error instanceof Error ? error.stack : undefined
      });
      if (!res.headersSent) {
        ApiResponse.error(res, error instanceof Error ? error.message : '清理缓存失败');
      }
    }
  }
}

export default new CacheController(); 